<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function axios({//形参对象解构语法
        url,
        method='GET',
        params={},
        data={}
                     }){
        return new Promise((resolve, reject)=>{
            //处理query参数，拼接到URL上
            let queryString = ''
            Object.keys(params).forEach(key=>{
                queryString += `${key}=${params[key]}&`
            })
            queryString = queryString.substring(0, queryString.length-1)
            if(queryString) {
                url += '?' + queryString
            }

            //执行ajax请求

            let request = new XMLHttpRequest()
            request.open(url, method)
            if(method === 'GET'){
                request.send()
            }else if(method === 'POST') {
                request.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
                request.send(JSON.stringify(data))//请求体数据必须是字符串，可以使urlencoded或者json，但必须是字符串
            }

            request.onreadystatechange = function(){
                if(request.readyState !== 4){
                    return;
                }
                const {status, statusText} = request.readyState
                if(status >= 200 && status <= 299){
                    const response = {
                        data: JSON.parse(request.response),
                        status,
                        statusText
                    }
                    resolve(response)
                }else{
                    reject(new Error(status + statusText))
                }
            }
        });
    }

</script>

</body>
</html>